/**
 * Created by Lwang on 2017/3/5.
 * 所有文章
 *
 */

import {square, ajax} from './resize.js';
import {way} from "./common.js";
import * as async from "async";
import $ from "jquery";
require("./layer.js");
require("./move.js");
import {weChat} from "./weChat.js";
var Handlebars = require("./handlebars.js");
require("./jquery.form.min.js");
require("./ajaxfileupload.js");
square(document, window);
var firstequal = location.href.indexOf("="),
    firstand = location.href.indexOf("&");
const courseid = firstand > -1 ? location.href.substring(firstequal + 1, firstand) : location.href.substr(firstequal + 1);
var deleteArr = [];                                         //删除的id列表
var deleteStr = "";                                         //删除id字符串
$(function () {
    let textInput = $("#j-word"),
        teacherHeadImg = "",
        teachimg = "",
        courseInfo, teacrerInfo, isBlod = 0, ispause = true,
        videoArr = [],
        getTimeCallback = null,
        timeoutQuickClick
        ;

    Handlebars.registerHelper("isShow", function (v1, v2, options) {
        if (v1 == v2) {
            return "display:block";
        } else {
            return "display:none";
        }
    });

    Handlebars.registerHelper("textTohtml", function (str) {
        return new Handlebars.SafeString(str);
    });


    way._login(() => {
        $.ajax({
            url: ajax.teacherInfo,
            xhrFields: {withCredentials: true},
            success: (res) => {
                teacrerInfo = res;
                teachimg = res.headImg;
                initContent();
            }
        });
    });
    //初始化课程内容
    function initContent() {
        $.ajax({
            url: ajax.course(courseid),
            xhrFields: {withCredentials: true},
            success: (res) => {
                courseInfo = res;
                var contents = res.contents,
                    d = new Date(res.createTime),
                    firstImg = "",
                    firstWord = "",
                    wordArr = [],
                    picArr = [];
                //处理文章详情列表
                var myTemplate = Handlebars.compile($("#listTemplate").html());
                $("#courseDetail").html(myTemplate(contents));

                $(".ae-img").find("img").attr("src", res.teacherHeadImg);
                teacherHeadImg = res.teacherHeadImg;
                $("title").html(res.title);
                $(".aet-title").html(res.title);
                $(".aet-date").html((d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getSeconds());
                $(".aet-num").html(res.count);

                //图片大小处理
                $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                    way.picSizeCtrl(obj, ".aec-picture");
                });

                $("#j-edit").click(function () {
                    $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                        way.picSizeCtrl(obj, ".aec-picture");
                    });
                });
                //分享配置
                $.each(contents, (index, obj) => {
                    if (obj.contentType == "IMAGE") {
                        picArr.push(obj.content);
                    } else if (obj.contentType == "TEXT") {
                        wordArr.push(obj.content);
                    }
                });

                picArr.length > 0 ? firstImg = picArr[0] : "http://m.studypointshare.com/images/c-eg.png";
                wordArr.length > 0 ? firstWord = wordArr[0] : "http://m.studypointshare.com/user-articles.html?courseid=" + res.id;
                $(".aec-audio").click(function () {
                    toPlay(this);
                });


                //分享初始化
                weChat.shareExe({
                    title: res.title, // 分享标题
                    desc: firstWord, // 分享描述
                    link: "http://m.studypointshare.com/user-articles.html?courseid=" + res.id, // 分享链接
                    imgUrl: firstImg, // 分享图标
                });

                //  点击图片预览
                $(".aec-picture").click(function () {
                    var self = this;
                    weChat.chooseImg($(self).find("img").attr("src"), picArr);
                });
            }
        });
    }

    //录音注册
    weChat.record("", function (serverid, time) {
        recordUpload(serverid, time);
    });
    //播放录音与暂停
    function toPlay(_self) {
        var timeout;
        var audio = $(_self).find(".j-audio")[0],
            self = _self,
            duration = audio.duration,
            trueduration = new Number($(self).find(".videonum").find("a").html()),
            currentTime = audio.currentTime;
            console.log(currentTime);
            console.log(currentTime);
        if (currentTime == 0) {
            audio.play();
            $(self).find(".playicon").find("img").attr("src", "images/play.gif");
            timeout = setTimeout(function () {
                $(self).find(".playicon").find("img").attr("src", "images/audio.png");
            }, trueduration * 1000);
        } else if (currentTime == duration) {
            audio.load();
            audio.play();
            $(self).find(".playicon").find("img").attr("src", "images/play.gif");
            timeout = setTimeout(function () {
                $(self).find(".playicon").find("img").attr("src", "images/audio.png");
            }, trueduration * 1000);
        } else {
            if (ispause) {
                trueduration = trueduration - currentTime;
                timeout = setTimeout(function () {
                    $(self).find(".playicon").find("img").attr("src", "images/audio.png");
                }, trueduration * 1000);
                audio.play();
                $(self).find(".playicon").find("img").attr("src", "images/play.gif");
            } else {
                console.log(4565)
                clearTimeout(timeout);
                audio.pause();
                $(self).find(".playicon").find("img").attr("src", "images/audio.png");
            }
            ispause = !ispause;
        }

    }


    //录音上传与回写

    function recordUpload(media_id, time) {
        const index = getIndex();
        layer.open({
            type: 2,
            message: "正在加载"
        });
        async.waterfall([() => {
            const data = {
                "content": "http://m.studypointshare.com/mp3/" + media_id + ".mp3",
                "contentType": "VIDEO",
                "courseId": courseid,
                duration: time,
                "sort": 0,
                "status": "ENABLED"
            };
            $.ajax({
                url: ajax.addContent,
                type: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                data: JSON.stringify(data),
                xhrFields: {
                    withCredentials: true
                },
                success: (res) => {
                    layer.closeAll();
                    if (index === 0) {
                        courseInfo.contents.unshift(res);
                    } else if (index === -1) {
                        courseInfo.contents.push(res);
                    } else {
                        courseInfo.contents.splice(index, 0, res);
                    }
                    var myTemplate = Handlebars.compile($("#listTemplate").html());
                    $("#courseDetail").eq(0).html(myTemplate(courseInfo.contents));
                    $(".ae-img").find("img").attr("src", teacherHeadImg);
                    //初始化录音
                    $(".aec-audio").click(function () {
                        toPlay(this);
                    });


                    //  点击图片预览
                    var picArr = [];
                    $.each(courseInfo.contents, (index, obj) => {
                        if (obj.contentType == "IMAGE") {
                            picArr.push(obj.content);
                        }
                    });
                    $(".aec-picture").click(function () {
                        var self = this;
                        weChat.chooseImg($(self).find("img").attr("src"), picArr);
                    });

                    //图片大小处理
                    $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                        way.picSizeCtrl(obj, ".aec-picture");
                    });


                }
            });
        }], () => {
            layer.closeAll();
            layer.open({
                type: 1,
                content: "网络异常, 请重试!"
            });
        });
    }

    //  图片上传与回写
    function upload(file) {
        const index = getIndex();
        layer.open({
            type: 2,
            content: "正在加载"
        });

        $("#head-form").ajaxSubmit({
            "type": "post",
            "dataType": "json",
            "url": ajax.upload + "?space=uquiz_image",
            "success": function (resopnse) {
                let id = resopnse.id,
                    data = {
                        "content": ajax.file(id),
                        "contentType": "IMAGE",
                        "courseId": courseid,
                        "id": id,
                        duration: 0,
                        "sort": 0,
                        "status": "ENABLED"
                    };
                if (id) {
                    $.ajax({
                        url: ajax.addContent,
                        type: "POST",
                        headers: {
                            "Content-Type": "application/json;charset=UTF-8"
                        },
                        data: JSON.stringify(data),
                        xhrFields: {
                            withCredentials: true
                        },
                        success: (res) => {
                            layer.closeAll();

                            if (index === 0) {
                                courseInfo.contents.unshift(res);
                            } else if (index === -1) {
                                courseInfo.contents.push(res);
                            } else {
                                courseInfo.contents.splice(index, 0, res);
                            }
                            var myTemplate = Handlebars.compile($("#listTemplate").html());
                            $("#courseDetail").eq(0).html(myTemplate(courseInfo.contents));
                            $(".ae-img").find("img").attr("src", teacherHeadImg);
                            //初始化录音
                            $(".aec-audio").click(function () {
                                toPlay(this);
                            });

                            //  点击图片预览
                            var picArr = [];
                            $.each(courseInfo.contents, (index, obj) => {
                                if (obj.contentType == "IMAGE") {
                                    picArr.push(obj.content);
                                }
                            });
                            $(".aec-picture").click(function () {
                                var self = this;
                                weChat.chooseImg($(self).find("img").attr("src"), picArr);
                            });

                            //图片大小处理
                            $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                                way.picSizeCtrl(obj, ".aec-picture");
                            });

                        }
                    });
                }
            }
        });
    }

    //  添加内容与回写
    function addContent(content) {
        const index = getIndex();
        layer.open({
            type: 2,
            content: "正在加载"
        });
        async.waterfall([() => {
            const data = {
                "content": content,
                "contentType": "TEXT",
                "courseId": courseid,
                "id": courseid,
                duration: 0,
                "sort": 0,
                "status": "ENABLED"
            };
            $.ajax({
                url: ajax.addContent,
                type: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                data: JSON.stringify(data),
                xhrFields: {
                    withCredentials: true
                },
                success: (res) => {
                    layer.closeAll();
                    if (index === 0) {
                        courseInfo.contents.unshift(res);
                    } else if (index === -1) {
                        courseInfo.contents.push(res);
                    } else {
                        courseInfo.contents.splice(index, 0, res);
                    }
                    var myTemplate = Handlebars.compile($("#listTemplate").html());
                    $("#courseDetail").eq(0).html(myTemplate(courseInfo.contents));

                    $(".ae-img").find("img").attr("src", teacherHeadImg);
                    //初始化录音
                    $(".aec-audio").click(function () {
                        toPlay(this);
                    });

                    //  点击图片预览
                    var picArr = [];
                    $.each(courseInfo.contents, (index, obj) => {
                        if (obj.contentType == "IMAGE") {
                            picArr.push(obj.content);
                        }
                    });
                    $(".aec-picture").click(function () {
                        var self = this;
                        weChat.chooseImg($(self).find("img").attr("src"), picArr);
                    });


                    //图片大小处理
                    $.each($("#courseDetail li").find(".aec-picture").find("img"), function (index, obj) {
                        way.picSizeCtrl(obj, ".aec-picture");
                    });

                }
            });
        }], () => {
            layer.closeAll();
            layer.open({
                type: 1,
                content: "网络异常, 请重试!"
            });
        });
    }


    //  加粗
    $("div.be-bold").on("touchend", () => {
        clearTimeout(timeoutQuickClick);
        timeoutQuickClick = setTimeout(function () {
            isBlod++;
            if (isBlod % 2 != 0) {
                $(".beb-true").css("display", "block");
                $(".beb-false").css("display", "none");
            } else {
                $(".beb-true").css("display", "none");
                $(".beb-false").css("display", "block");
            }
            document.execCommand("bold", false, null);
        }, 300);

    });

    //  添加内容
    $(".be-send").on("click", () => {
        // let content = editor.body.innerHTML.replace(/\<b\>/gim, "<b style='font-weight: bold;'>");
        let content = $("#j-word").html();
        if (!content) {
            layer.open({
                type: 1,
                content: "请先输入内容!"
            });
            return;
        }
        addContent(content);
        $("#j-word").html("");
    });

    //  文件上传
    $("input.be-upload").on("change", (e) => {
        const file = $("input.be-upload").get(0).files[0];
        if (file.size < 5000000) {
            upload(file);
        } else {
            layer.open({
                type: 1,
                content: "选择的图片大小不得超过5兆!",
                time: 1
            });
        }
        e.preventDefault();
    });

    //  完成
    $("#j-completeBtn").on("click", (e) => {
        const title = $("input.atew-input").val().trim();
        if (!title) {
            layer.open({
                type: 1,
                content: "请先输入标题!"
            });
            return;
        }
        if (!courseInfo.contents.length) {
            layer.open({
                type: 1,
                content: "请先添加内容!"
            });
            return;
        }

        courseInfo.contents = courseInfo.contents.map((item, index) => {
            item.courseId = courseid;
            item.id = courseid;
            item.sort = 0;
            item.status = "ENABLED";
            return item;
        });

        const data = {
            title,
            contents: courseInfo.contents,
            courseId: courseid,
            teacherId: teacrerInfo.id,
            id: courseid,
            sort: 0,
            status: "ENABLED"
        };

        $.ajax({
            url: ajax.couseEdit,
            type: "POST",
            headers: {
                "Content-Type": "application/json;charset=UTF-8"
            },
            data: JSON.stringify(data),
            xhrFields: {
                withCredentials: true
            },
            success: (res) => {
                layer.closeAll();
                layer.open({
                    type: 1,
                    content: "发布成功!即将返回首页!"
                });
                setTimeout(() => {
                    location.href = "/newest.html";
                }, 2000);
            }
        });
    });

    //  相关事件
    $(".ber-record").click(function () {
        $(this).css("display", "none");
        $(".ber-key").css("display", "block");
        $("#j-word").css("display", "none");
        $(".no-press").css("display", "block");
        $(".has-press").css("display", "none");
        $(".be-img").css("display", "block");
        $(".be-send").css("display", "none");
    });
    $(".ber-key").click(function () {
        $(this).css("display", "none");
        $("#j-word").css("display", "block");
        $(".ber-record").css("display", "block");
        $(".no-press").css("display", "none");
        $(".has-press").css("display", "none");
        $(".be-img").css("display", "none");
        $(".be-send").css("display", "block");
    });


    function getIndex() {
        let item = [].slice.call($("#courseDetail>li")),
            line = $("div.move-pos"),
            posLine = line.position(),
            htmlFs = parseFloat($("html").css("fontSize")),
            abs = htmlFs * 0.5,
            lineTop = posLine.top,
            cur, curTop;
        if (line.css("opacity") == 0) {
            return -1;
        }
        item = item.filter((el) => $(el).css("display") != "none");
        for (let i = 0, len = item.length; i < len; i++) {
            cur = $(item[i]);
            curTop = cur.position().top;
            if (cur.css("display") !== "none" && curTop >= lineTop) {
                return i;
            }
        }
        return -1;
    }

    //删除按钮
    $(document).on("click", ".aec-choose", function () {
        var self = this;
        var ischeck = $(self).find(".aecc-input").get(0).checked;
        if (ischeck) {
            $(self).find(".aecc-img").css({
                "background": 'url(images/circle-choose.png) right center no-repeat',
                "backgroundSize": "1rem,1rem"
            });
            deleteArr.push($(self).parent().find(".hiddenId").val());
        } else {
            $(self).find(".aecc-img").css({
                "background": 'url(images/circle.png) right center no-repeat',
                "backgroundSize": "1rem,1rem"
            });
            deleteArr.forEach((obj, index) => {
                if (obj == $(self).parent().find(".hiddenId").val()) {
                    deleteArr.splice(index, 1);
                }
            })
        }

    });

    //删除接口
    $("#j-delete").click(function () {
        if (deleteArr.length == 0) {
            layer.open({
                type: "1",
                content: "请先选择需要删除的课程"
            })
        } else {
            $.ajax({
                url: ajax.contentsDel,
                type: "POST",
                data: {
                    id: deleteArr
                },
                xhrFields: {
                    withCredentials: true
                },
                traditional: true,//这里设置为true
                success: (res) => {
                    if (!res.code) {
                        initContent();
                        //按钮隐藏
                        $(".jd-show").hide();
                        $("#j-complete").css("display", "none");
                        $("#j-top").css("display", "block");
                        $('.j-blank').css("height", "4rem");
                        $(".move-pos").css("opacity", "0");
                    } else {
                        layer.open({
                            type: 1,
                            content: res.message
                        })
                    }
                }
            });
        }
    });

    //监听focus
    $("#j-word").focus(function () {
        setTimeout(function () {
            var scrollH = $(document).scrollTop(),
                nowScrollH = scrollH + 100;
            $(document).scrollTop(nowScrollH);
        },400);
    })

});


